import upath from "upath";
import gulpInject from "gulp-inject";
import { src, dest } from "gulp";
import { Print } from "../utils/index";
import { pathExistsSync } from "fs-extra";
import { FileTask } from "../utils/baseTaskClass";

export class HtmlCompile extends FileTask {
  /**
   * 插入CSS文件链接至HTML
   * @param target 目标CSS文件路径
   */
  insertLinkCss(target: string): NodeJS.ReadableStream | void {
    if (!/\.css$/.test(target)) {
      // 去除路径尾部/字符
      target = target.replace(/\/$/, "") + "/*.css";
    }
    if (!pathExistsSync(upath.dirname(target))) {
      return Print.error("CSS目录不存在");
    }
    return this.instance.pipe(gulpInject(
      src(target, { read: false }),
      {
        // 输出文件内的引用是否使用相对路径
        relative: true,
        starttag: "<!-- links:START -->",
        endtag: "<!-- links:END -->"
      }
    ));
  }

  // 保存并输出文件
  save(path: string, instance: NodeJS.ReadableStream = this.instance) {
    instance.pipe(dest(path));
  }
}
